package protocol;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.jboss.netty.buffer.ChannelBuffer;

import util.ProtocolUtils;

public class BasicProtocol implements Iprotocol {
	
	protected int	Type	= 0;
	
	@Override
	public void setType(int Type) {
		
	}
	
	@Override
	public int getType() {
		
		return 0;
	}
	
	@Override
	public byte[] write() {
		
		return null;
	}
	
	/**
	 * 打包进目标流
	 * 
	 * @param outputStream
	 * @param _byteArr
	 * @return
	 */
	public ByteArrayOutputStream enCodeFormat(ByteArrayOutputStream outputStream, byte[] _byteArr) {
		
		try {
			outputStream.write(_byteArr);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("BasicProtocol--enCodeFormat---");
		}
		
		return outputStream;
	}
	
	public ByteArrayOutputStream enCodeString(ByteArrayOutputStream outputStream, String str) {
		
		byte[] strbyt = str.getBytes();
		byte[] strLength=ProtocolUtils.int2byteArray(str.length());
		
		enCodeFormat(outputStream,strLength);
		enCodeFormat(outputStream, strbyt);
		return outputStream;
	}
	
	@Override
	public void read(ChannelBuffer buffer) {
		
	}
	
	public String decodeString(ChannelBuffer buffer) {
		int nameLength = buffer.readShort();
		
		byte[] nameByteArr = new byte[nameLength];
		buffer.readBytes(nameByteArr, 0, nameLength);
		
		return new String(nameByteArr);
	}
}
